package sample;

import java.awt.Color;
import java.awt.geom.Point2D;
import java.io.IOException;

import robocode.HitRobotEvent;
import robocode.ScannedRobotEvent;
import robocode.TeamRobot;

public class RoboAR extends TeamRobot {

	private boolean safe = false;
	private double direction = 1;
	@Override
	public void run() {
		setRadarColor(Color.RED);
		while(true){
			turnRadarLeft(360);
		}
	}
	
	@Override
	public void onScannedRobot(ScannedRobotEvent event) {
		if( !event.getName().startsWith("sample.RoboS")
				&& !event.getName().startsWith("sample.RoboAR")
				&& event.getDistance() <= 100) {
			if( event.getDistance() < 50 ){
				stop();
//				turnRight(45);
//				direction = -0.4;
			}
			clearAllEvents();
			if( !safe ){
				try {
					broadcastMessage(event.getName());
				} catch (IOException e) {
					e.printStackTrace();
				}				
				double b = Math.toRadians(event.getBearing()+this.getHeading());
				double x = this.getX() + event.getDistance()*Math.sin(b);
				double y = this.getY() + event.getDistance()*Math.cos(b);
				direction = 1;
				goTo(new Point2D.Double(x,y));
			}else{
				try {
					broadcastMessage("safe");
				} catch (IOException e) {
					e.printStackTrace();
				}	
				doNothing();
			}
			if( this.getX() < 70 || this.getX() > 1430 ) safe = true;
			execute();
		}
	}
	
	@Override
	public void onHitRobot(HitRobotEvent event) {
		stop();
	}
	
    private double absoluteBearingRadians(Point2D source, Point2D target) {
        return Math.atan2(target.getX() -
            source.getX(), target.getY() - source.getY());
    }

    private double normalRelativeAngleRadians(double angle) {
        return Math.atan2(Math.sin(angle), Math.cos(angle));
    }

    private Point2D getRobotLocation() {
        return new Point2D.Double(getX(), getY());
    }
    
    private void goTo(Point2D point) {
        setTurnRightRadians(
            normalRelativeAngleRadians(
                absoluteBearingRadians(getRobotLocation(), point) - getHeadingRadians()
            )
         );
        execute();
        setAhead(getRobotLocation().distance(point)*direction-10);
//        setAhead(100*direction-10);
    }	
	
}
